package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.pojo.Nursecontent;
import com.neudu.yiyang.pojo.Nurselevel;
import com.neudu.yiyang.pojo.Nurselevelitem;
import com.neudu.yiyang.service.NursecontentService;
import com.neudu.yiyang.service.NurselevelService;
import com.neudu.yiyang.service.NurselevelitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class NurseLevelController {

    @Autowired
    private NurselevelService nurselevelService;

    @Autowired
    private NurselevelitemService nurselevelitemService;

    @Autowired
    private NursecontentService nursecontentService;

    @Autowired
    private JSONReturn jsonReturn;

    /**
     * 添加护理级别
     */
    @RequestMapping("addNurseLevel")
    public String addNurseLevel(@RequestBody Nurselevel nurselevel) {
        try {
            // 检查必填字段
            if (ObjectUtils.isEmpty(nurselevel.getLevelId())) {
                return jsonReturn.returnError("护理级别名称不能为空");
            }
            // 初始化逻辑删除状态为未删除
            nurselevel.setIsDeleted(0);
            boolean save = nurselevelService.save(nurselevel);
            if (save) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("添加护理级别失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("添加护理级别失败：" + e.getMessage());
        }
    }
    @RequestMapping("getNurseLevelById")
    public String getNurseLevelById(@RequestParam("id") Integer id) {
        try {
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("查询失败，ID不能为空");
            }
            Nurselevel nurselevel = nurselevelService.getById(id);
            if (nurselevel == null || nurselevel.getIsDeleted() == 1) {
                return jsonReturn.returnError("未找到对应的护理级别");
            }
            return jsonReturn.returnSuccess(nurselevel);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询护理级别失败：" + e.getMessage());
        }
    }

    /**
     * 更新护理级别
     */
    @RequestMapping("updateNurseLevel")
    public String updateNurseLevel(@RequestBody Nurselevel nurselevel) {
        try {
            // 检查ID是否存在
            if (ObjectUtils.isEmpty(nurselevel.getId())) {
                return jsonReturn.returnError("更新失败，ID不能为空");
            }
            // 检查记录是否存在（未被删除）
            LambdaQueryWrapper<Nurselevel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Nurselevel::getId, nurselevel.getId())
                    .eq(Nurselevel::getIsDeleted, 0);
            Nurselevel existLevel = nurselevelService.getOne(queryWrapper);
            if (ObjectUtils.isEmpty(existLevel)) {
                return jsonReturn.returnError("更新失败，未找到对应的护理级别");
            }
            boolean update = nurselevelService.updateById(nurselevel);
            if (update) {
                return jsonReturn.returnSuccess(nurselevel);
            } else {
                return jsonReturn.returnError("更新护理级别失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("更新护理级别失败：" + e.getMessage());
        }
    }

    /**
     * 删除护理级别（逻辑删除）
     */
    @RequestMapping("removeNurseLevel")
    public String removeNurseLevel(@RequestParam("id") Integer id) {
        try {
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("删除失败，ID不能为空");
            }
            // 执行逻辑删除（设置is_deleted=1）
            Nurselevel nurselevel = new Nurselevel();
            nurselevel.setId(id);
            nurselevel.setIsDeleted(1);
            boolean remove = nurselevelService.updateById(nurselevel);
            if (remove) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("删除护理级别失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除护理级别失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询护理级别列表（带条件搜索）
     */
    @RequestMapping("listNurseLevel")
    public String listNurseLevel(
            Nurselevel nurselevel,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize
    ) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Nurselevel> queryWrapper = new LambdaQueryWrapper<>();
            // 条件查询
            if (!ObjectUtils.isEmpty(nurselevel.getLevelId())) {
                queryWrapper.like(Nurselevel::getLevelId, nurselevel.getLevelId());
            }
            if (nurselevel.getLevelStatus() != null) {
                queryWrapper.eq(Nurselevel::getLevelStatus, nurselevel.getLevelStatus());
            }
            queryWrapper.eq(Nurselevel::getIsDeleted, 0); // 排除已删除记录
            List<Nurselevel> list = nurselevelService.list(queryWrapper);
            PageInfo<Nurselevel> pageInfo = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询护理级别列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据护理级别查询护理项目（不分页）
     */
    @RequestMapping("listNurseItemByLevel")
    public String listNurseItemByLevel(@RequestParam("levelId") Integer levelId) {
        try {
            if (ObjectUtils.isEmpty(levelId)) {
                return jsonReturn.returnError("查询失败，levelId不能为空");
            }
            // 通过Nurselevelitem关联查询护理项目
            LambdaQueryWrapper<Nurselevelitem> itemQuery = new LambdaQueryWrapper<>();
            itemQuery.eq(Nurselevelitem::getLevelId, levelId);
            List<Nurselevelitem> itemList = nurselevelitemService.list(itemQuery);
            List<Integer> itemIds = itemList.stream().map(Nurselevelitem::getItemId).toList();
            LambdaQueryWrapper<Nursecontent> contentQuery = new LambdaQueryWrapper<>();
            contentQuery.in(Nursecontent::getId, itemIds);
            List<Nursecontent> contentList = nursecontentService.list(contentQuery);
            return jsonReturn.returnSuccess(contentList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询护理项目失败：" + e.getMessage());
        }
    }

    /**
     * 配置护理项目到护理级别（添加关联）
     */
    @RequestMapping("addItemToLevel")
    public String addItemToLevel(@RequestBody Nurselevelitem nurselevelitem) {
        try {
            if (ObjectUtils.isEmpty(nurselevelitem.getLevelId()) || ObjectUtils.isEmpty(nurselevelitem.getItemId())) {
                return jsonReturn.returnError("级别ID或项目ID不能为空");
            }
            // 检查是否已存在关联
            LambdaQueryWrapper<Nurselevelitem> existQuery = new LambdaQueryWrapper<>();
            existQuery.eq(Nurselevelitem::getLevelId, nurselevelitem.getLevelId())
                    .eq(Nurselevelitem::getItemId, nurselevelitem.getItemId());
            long count = nurselevelitemService.count(existQuery);
            if (count > 0) {
                return jsonReturn.returnError("当前级别已存在该护理项目");
            }
            boolean save = nurselevelitemService.save(nurselevelitem);
            if (save) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("添加关联失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("添加关联失败：" + e.getMessage());
        }
    }

    /**
     * 删除护理级别中的护理项目关联
     */
    @RequestMapping("removeNurseLevelItem")
    public String removeNurseLevelItem(
            @RequestParam("levelId") Integer levelId,
            @RequestParam("itemId") Integer itemId
    ) {
        try {
            if (ObjectUtils.isEmpty(levelId) || ObjectUtils.isEmpty(itemId)) {
                return jsonReturn.returnError("级别ID或项目ID不能为空");
            }
            LambdaQueryWrapper<Nurselevelitem> deleteQuery = new LambdaQueryWrapper<>();
            deleteQuery.eq(Nurselevelitem::getLevelId, levelId)
                    .eq(Nurselevelitem::getItemId, itemId);
            boolean remove = nurselevelitemService.remove(deleteQuery);
            if (remove) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("删除关联失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除关联失败：" + e.getMessage());
        }
    }
    @RequestMapping("toggleNurseLevelStatus")
    public String toggleNurseLevelStatus(@RequestParam("id") Integer id) {
        try {
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("操作失败，ID不能为空");
            }
            // 查询当前护理级别
            Nurselevel nurselevel = nurselevelService.getById(id);
            if (nurselevel == null || nurselevel.getIsDeleted() == 1) {
                return jsonReturn.returnError("未找到对应的护理级别");
            }
            // 切换状态
            if (nurselevel.getLevelStatus() == 1) {
                nurselevel.setLevelStatus(2);
            } else {
                nurselevel.setLevelStatus(1);
            }
            boolean update = nurselevelService.updateById(nurselevel);
            if (update) {
                return jsonReturn.returnSuccess(nurselevel);
            } else {
                return jsonReturn.returnError("切换护理级别状态失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("切换护理级别状态失败：" + e.getMessage());
        }
    }
}